package com.dx.mes.web.common.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.dx.common.table.ppt.Bis_uas_fnc_grp;
import com.dx.common.table.ppt.Bis_uas_grp;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.facade.uas.service.IBisUasFunGrpService;
import com.dx.mes.web.common.authorization.manager.TokenManager;
import com.dx.mes.web.common.authorization.model.TokenModel;
import com.dx.mes.web.common.config.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class PermissionInterceptor implements HandlerInterceptor {

    @Resource
    private IBisUasFunGrpService bisUasFunGrpService;
    @Autowired
    private TokenManager manager;

    //在执行handler之前来执行的
    //用于用户认证校验、用户权限校验
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("content-type", "text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        //得到请求的url
        String requestURI = request.getRequestURI();
        /*if (requestURI.contains("/mes-jn-web-tool" ) ||
			requestURI.contains("/mes-jn-web-spc")	||
			requestURI.contains("/mes-jn-web-bc")	||
			requestURI.contains("/mes-jn-web-brm")	||
			requestURI.contains("/mes-jn-web-plan")	||
			requestURI.contains("/mes-jn-web-process")	||
			requestURI.contains("/mes-jn-web-query")	||
			requestURI.contains("/mes-jn-web-warehouse") ) {
			String userId = (String) request.getSession().getAttribute("userid");
			if (userId == null) {
				request.getRequestDispatcher("/index.jsp").forward(request,response);
				return false;
			}
		}*/
        //判断如果是APP端登陆则卡控是否登陆
        // TODO: 2017/8/20 拦截器会拦截ajax请求返回false，注意新增ajax请求时来这里放行
        //判断是否为ajax请求
        if (requestURI.contains("kanban")) {
            return true;
        }
        if (requestURI.contains("checkUserAuthority.do") ||
                requestURI.contains("sendMsg.do") ||
                requestURI.contains("logout.do") ||
                requestURI.contains("home.do") ||
                requestURI.contains("editPwd.do") ||
                requestURI.contains("loginRtn.do") ||
                requestURI.contains("download.do") ||
                requestURI.contains("exportChartData.do")
                ) {

            String userID = (String) request.getSession().getAttribute("userid");
//			String authorization = request.getParameter(Constants.AUTHORIZATION);
            String authorization = request.getHeader(Constants.AUTHORIZATION);
            //验证token
            TokenModel model = manager.getToken(authorization);

            if (!StringUtils.isEmpty(userID) && model == null) {
                //首先判断是否为管理员
                List<Bis_uas_grp> adminList = bisUasFunGrpService.getAdminFlag(userID);
                if (adminList != null && adminList.size() > 0) {
                    return true;
                }
                //判断权限
                List<Bis_uas_fnc_grp> permission = bisUasFunGrpService.getPermission(userID);
                permission = permission == null ? new ArrayList<>() : permission;
                List<String> permissionList = permission.stream().map(p -> p.getId().getFunc_code_fk()).collect(toList());
                //List<String> perList = permissionList.stream().map(per -> per.substring(0, per.lastIndexOf("_"))).collect(toList());
                boolean hasAuth = permissionList.stream().anyMatch(requestURI::contains);
                if (hasAuth) {
                    return true;
                } else {
                    //执行到这里拦截，跳转到无权访问的提示页面
                    request.getRequestDispatcher("/refuse.jsp").forward(request, response);
                    return false;
                }
            }

            if (manager.checkToken(model)) {
                //如果token验证成功，将token对应的用户id存在request中，便于之后注入
//				request.setAttribute(Constants.CURRENT_USER_ID, model.getUserId());
//				JSONObject msgJson = new JSONObject();
//				msgJson.put("rtn_code","0000000");
//				msgJson.put("rtn_mesg","SUCCESS");
//				msgJson.put("userId",model.getUserId());
//				msgJson.put("token",model.getToken());
//				String outMsg = JacksonUtil.toJSONStr(msgJson);
//                response.getWriter().write(outMsg);
//                String outMsg = JacksonUtil.toJSONStr(msgJson);
//                response.getWriter().write(outMsg);
                return true;
            } else {
                JSONObject msgJson = new JSONObject();
                msgJson.put("rtn_code", "9999999");
                msgJson.put("rtn_mesg", "ERROR");
                String outMsg = JacksonUtil.toJSONStr(msgJson);
                response.getWriter().write(outMsg);
                return false;
            }
        }

        //如果返回false表示拦截不继续执行handler，如果返回true表示放行
        return false;
    }

    //在执行handler返回modelAndView之前来执行
    //如果需要向页面提供一些公用 的数据或配置一些视图信息，使用此方法实现 从modelAndView入手
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    //执行handler之后执行此方法
    //作系统 统一异常处理，进行方法执行性能监控，在preHandle中设置一个时间点，在afterCompletion设置一个时间，两个时间点的差就是执行时长
    //实现 系统 统一日志记录
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }


}
